/**
 * create by young (young2f@outlook.com) on 2020/12/3
 */
'use strict';
const { Service } = require('egg');
const _ = require('lodash');
const moment = require('moment');

module.exports = class extends Service {
  isNumber(value) {
    return /^-?\d+(\.\d+)?$/.test(value);
  }

// "13%", "9%", "6%", "3%", "1%", "0%"
  getTax(amount=0, taxRate = '0%') {
    switch (taxRate) {
      case '0%':
        return amount;
      case '13%':
        return (amount / 1.13 * 0.13).toFixed(2);
      case '9%':
        return (amount / 1.09 * 0.09).toFixed(2);
      case '6%':
        return (amount / 1.06 * 0.06).toFixed(2);
      case '3%':
        return (amount / 1.03 * 0.03).toFixed(2);
      case '1%':
        return (amount / 1.01 * 0.01).toFixed(2);
      default:
        return 0;
    }
  }

  getValue = (_type, value, key) => {
    if (_type === 'date') {
      console.log('日期', value);
      if (key.includes('.')) {
        console.log('下一级日期，需要转换');
        return {
          $gte: moment(value[0])
            .startOf('day')
            .valueOf(),
          $lt: new moment(value[1])
            .endOf('day')
            .valueOf()
        };
      }
      if (value.length === 2) {
        return {
          $gte: new Date(moment(value[0])
            .startOf('day')
            .valueOf()),
          $lt: new Date(moment(value[1])
            .endOf('day')
            .valueOf())
        };
      }
      return {
        $gte: new Date(moment(value)
          .startOf('day')
          .valueOf()),
        $lt: new Date(moment(value)
          .endOf('day')
          .valueOf())
      };
    }
    if (_type === 'string' || _type === 'select') {
      return { $regex: value };
    }
    if (_type === 'number') {
      const t = value.charAt(0);
      const number = value.substring(1);
      if (!this.isNumber(number)) {
        throw new Error(`数字查询条件错误：${key},${value} `);
      }
      const _number = parseFloat(number);
      if (t !== '<' && t !== '>' && t !== '=' && this.isNumber(number)) {
        return { $eq: _number };
      } else {
        if (t === '<') {
          return { $lt: _number };
        }
        if (t === '>') {
          return { $gt: _number };
        }
        if (t === '=') {
          return { $eq: _number };
        }
      }
    }
    return undefined;
  };
};
